<?php 

class Functionary_Model extends grocery_CRUD_Model 
{
    
    /*
     * Realiza la consulta para obtener datos de la tabla seleccioanda
     */
    
    function get_list()
    {
    	if($this->table_name === null)
    		return false;
    	$select = "{$this->table_name}.*";
        $select .= ",USUARIO.EMP_ID,USUARIO.USUA_NOMBRES,USUARIO.USUA_APELLIDOS,USUARIO.USUA_CEDULA,USUARIO.USUA_CORREO,USUARIO.USUA_TELEFONO";
    	$this->db->select($select, false);	
    	$results = $this->db->get($this->table_name)->result();	
    	return $results;
    }
    
    /*
     * Establece la informacion de cada una de las columnas que se deben recuperar
     */
    function get_field_types_basic_table()
    {
    	$db_field_types = array();
        $db_query_result_funcionarity=$this->db->query("SHOW COLUMNS FROM `{$this->table_name}`")->result();
        $db_query_result_user=$this->db->query("SHOW COLUMNS FROM USUARIO")->result();
        $db_query_result_chargue=$this->db->query("SHOW COLUMNS FROM FUNCIONARIODESEMPENIACARGO")->result();
        $db_merge_result = array_merge((array)$db_query_result_user,(array)$db_query_result_funcionarity,(array)$db_query_result_chargue);
        $db_merge_result = array_merge((array)$db_query_result_user,(array)$db_query_result_funcionarity);
    	foreach($db_merge_result as $db_field_type)
    	{
    		$type = explode("(",$db_field_type->Type);
    		$db_type = $type[0];
    		
    		if(isset($type[1]))
    		{
    			if(substr($type[1],-1) == ')')
    			{
    				$length = substr($type[1],0,-1);
    			}
    			else
    			{
    				list($length) = explode(" ",$type[1]);
    				$length = substr($length,0,-1);
    			}
    		}
    		else 
    		{
    			$length = '';
    		}
    		$db_field_types[$db_field_type->Field]['db_max_length'] = $length;
    		$db_field_types[$db_field_type->Field]['db_type'] = $db_type;
    		$db_field_types[$db_field_type->Field]['db_null'] = $db_field_type->Null == 'YES' ? true : false;
    		$db_field_types[$db_field_type->Field]['db_extra'] = $db_field_type->Extra;
    	}

    	$results_user = $this->db->field_data("USUARIO");
        $results_functionary = $this->db->field_data($this->table_name);
        $results_chargue = $this->db->field_data("FUNCIONARIODESEMPENIACARGO");
        $results=array_merge( (array)$results_user,(array)$results_functionary,(array)$results_chargue);
        $results=array_merge( (array)$results_user,(array)$results_functionary);
    	foreach($results as $num => $row)
    	{
            
    		$row = (array)$row;
    		$results[$num] = (object)( array_merge($row, $db_field_types[$row['name']])  );
    	}
    	
    	return $results;
    }
  
    /*
     * Recupera los valores que se van a editar
     */
    function get_edit_values($primary_key_value)
    {
        $select = "{$this->table_name}.*";
        $select .= ",USUARIO.USUA_NOMBRES,USUARIO.USUA_APELLIDOS,USUARIO.USUA_CEDULA,USUARIO.USUA_CORREO,USUARIO.USUA_TELEFONO";
        $this->db->where('USUARIO.USUA_ID',$primary_key_value);
	$this->db->join('USUARIO','USUARIO.USUA_ID = FUNCIONARIO.USUA_ID');
    	$result = $this->db->get($this->table_name)->row();
        $extended_data= new stdClass;
        $extended_data->VER_FUNC_CONTRASENA=$result->FUNC_CONTRASENA;
        $full_data = (object) array_merge((array)$result, (array)$extended_data);
    	return $full_data;
    }
    
    /*
     * Recibe los valores ya editados para ser alamacenados
     */
    
    function db_update($post_array, $primary_key_value)
    {
    	$primary_key_field = $this->get_primary_key();
        $user_data=array();
        $fuctionary_data=array();
        $chargue_functionary_data=array();
        
        $user_data['EMP_ID'] = $post_array['EMP_ID'];
        $user_data['USUA_NOMBRES'] = $post_array['USUA_NOMBRES'];
        $user_data['USUA_APELLIDOS'] = $post_array['USUA_APELLIDOS'];
        $user_data['USUA_CORREO'] = $post_array['USUA_CORREO'];
        $user_data['USUA_CEDULA'] = $post_array['USUA_CEDULA'];
        $user_data['USUA_DIRECCIONRESIDENCIA'] = $post_array['USUA_DIRECCIONRESIDENCIA'];
        $user_data['USUA_TELEFONO'] = $post_array['USUA_TELEFONO'];
        $user_data['USUA_CELULAR'] = $post_array['USUA_CELULAR'];
        
        $fuctionary_data['FUNC_USUARIO'] = $post_array['FUNC_USUARIO'];
        $fuctionary_data['FUNC_CONTRASENA'] = $post_array['FUNC_CONTRASENA'];
        
        $chargue_functionary_data['FDC_FECHAVINCULACION'] = $post_array['FDC_FECHAVINCULACION'];
        $chargue_functionary_data['FDC_FECHADESVINCULACION'] = $post_array['FDC_FECHADESVINCULACION'];
        $chargue_functionary_data['FDC_ESTADOCARGO'] = $post_array['FDC_ESTADOCARGO'];
        $chargue_functionary_data['FDC_MOTIVO'] = $post_array['FDC_MOTIVO'];
        
        $update_user=$this->db->update("USUARIO",$user_data, array( $primary_key_field => $primary_key_value));
        $update_functionary=$this->db->update($this->table_name,$fuctionary_data, array( $primary_key_field => $primary_key_value));
        $update_FDC=$this->db->update("FUNCIONARIODESEMPENIACARGO",$chargue_functionary_data, array( "USUA_ID" =>$primary_key_value,"CAR_ID" =>$primary_key_value));
    	return $update_user&&$update_functionary && $update_FDC;
    }    
    /*
     * Recibe los valores ingresados en el formulario de crear
     */
    function db_insert($post_array)
    {
        $user_data=array();
        $fuctionary_data=array();
        $chargue_functionary_data=array();
        
        $user_data['EMP_ID'] = $post_array['EMP_ID'];
        $user_data['USUA_NOMBRES'] = $post_array['USUA_NOMBRES'];
        $user_data['USUA_APELLIDOS'] = $post_array['USUA_APELLIDOS'];
        $user_data['USUA_CORREO'] = $post_array['USUA_CORREO'];
        $user_data['USUA_CEDULA'] = $post_array['USUA_CEDULA'];
        $user_data['USUA_DIRECCIONRESIDENCIA'] = $post_array['USUA_DIRECCIONRESIDENCIA'];
        $user_data['USUA_TELEFONO'] = $post_array['USUA_TELEFONO'];
        $user_data['USUA_CELULAR'] = $post_array['USUA_CELULAR'];
        
    	$insert = $this->db->insert("USUARIO",$user_data);
    	if($insert)
    	{
    		$id=$this->db->insert_id();
                
                $fuctionary_data['USUA_ID'] = $id;
                $fuctionary_data['FUNC_USUARIO'] = $post_array['FUNC_USUARIO'];
                $fuctionary_data['FUNC_CONTRASENA'] = $post_array['FUNC_CONTRASENA'];
                $insert = $this->db->insert("FUNCIONARIO",$fuctionary_data);
                if($insert)
                {
                    $chargue_functionary_data['CAR_ID']=1;
                    $chargue_functionary_data['USUA_ID']=$id;
                    $chargue_functionary_data['FDC_FECHAVINCULACION'] = date('Y-m-d H:i:s');
                    $chargue_functionary_data['FDC_FECHADESVINCULACION'] = $post_array['FDC_FECHADESVINCULACION'];
                    $chargue_functionary_data['FDC_ESTADOCARGO'] = $post_array['FDC_ESTADOCARGO'];
                    $chargue_functionary_data['FDC_MOTIVO'] = $post_array['FDC_MOTIVO'];
                    $insert = $this->db->insert("FUNCIONARIODESEMPENIACARGO",$chargue_functionary_data);
                    if($insert)return $id;
                    return false;
                }

                return false;
    	}
    	return false;
    }
    
    /*
     * Recupera la llave primaria del elemento que se desea eliminar
     */
    function db_delete($primary_key_value)
    {
    	$primary_key_field = $this->get_primary_key();
    	
    	if($primary_key_field === false)
    		return false;
    	
    	$this->db->limit(1);
    	$this->db->delete($this->table_name,array( $primary_key_field => $primary_key_value));
    	if( $this->db->affected_rows() != 1)
    		return false;
    	else
    		return true;
    }
    
    /*
     * Formatea las relaciones 1-n
     */
    function join_relation($field_name , $related_table , $related_field_title)
    {
		$related_primary_key = $this->get_primary_key($related_table);
		
		if($related_primary_key !== false)
		{
                        $this->db->join('USUARIO','USUARIO.USUA_ID = FUNCIONARIO.USUA_ID');
			$this->db->join( "EMPRESA" , "EMPRESA.EMP_ID=USUARIO.EMP_ID",'LEFT');
			$this->relation[$field_name] = array($field_name , $related_table , $related_field_title);
			return true;
		}
                return false;
    }
    
}

?>